<?php
declare (strict_types = 1);

namespace app\admin\service;

use app\BaseService;
use app\common\exception\Http;
use app\common\model\admin\Admin;
use thans\jwt\facade\JWTAuth;
use think\facade\Env;

class LoginService  extends BaseService
{
    public $model;

    public function __construct(Admin $model)
    {
        $this->model = $model;
    }

    /**
     * 密码登录
     * User Reborn
     * Time 2020/4/3 15:02
     * @param string $login_name
     * @param string $password
     * @return array|\think\Model|null
     * @throws Http
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(string $login_name,string $password)
    {
        $user = $this->model->where('login_name|mobile',$login_name)->find();

        if (empty($user)) {
            throw new Http('用户不存在');
        }

//        if(!$this->verifyPassword($user,$password)){
//            throw new Http('密码错误');
//        }

        return $user;
    }


    /**
     * 验证用户密码
     * User Reborn
     * Time 2020/4/9 15:08
     * @param Admin $admin
     * @param string $password
     * @return bool
     */
    public function verifyPassword(Admin $admin,string $password)
    {
        $pwd_peppered = hash_hmac('sha256', $password, Env::get('salt.key'));

        return \password_verify($pwd_peppered, $admin->password);
    }

    /**
     * 生成token
     * User Reborn
     * Time 2020/4/9 15:07
     * @param Admin $admin
     * @return string
     */
    public function makeToken(Admin $admin)
    {
        return JWTAuth::builder(['uid'=>$admin->admin_id]);
    }
}
